#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <sys/stat.h>

#include <stdarg.h>

#include <time.h>

#include "tool_log.h"

static const char *const logdir = "/tmp/elitah";
static const char *const logpath = "/tmp/elitah/server.log";
static const char *const logformat = "%04d-%02d-%02d%c%s%c%02d:%02d:%02d\t\t%s\r\n";
static const char *const wday[] = {"Sun(7)", "Mon(1)", "Tue(2)", "Wed(3)", "Thu(4)", "Fri(5)", "Sat(6)"};

int init_logdir(void)
{
	if(0 == access(logdir, F_OK))
	{
		return EXIT_SUCCESS;
	}
	else
	{
		mkdir(logdir, 0777);
	}
	if(0 == access(logdir, F_OK))
	{
		logout("The log folder is created successfully...");
		return EXIT_SUCCESS;
	}
	else
	{
		return EXIT_FAILURE;
	}
}

void logoutf(const char *format, ...)
{
	char strbuf[1024] = {0};
	va_list args;
	va_start(args, format);
	vsnprintf(strbuf, sizeof(strbuf), format, args);
	logout(strbuf);
	va_end(args);
}

void logout(const char *log_str)
{
	time_t tmt;
	struct tm *p;

	FILE *pf = NULL;

	if(EXIT_SUCCESS != init_logdir())
	{
		return;
	}

	tmt = time(NULL) + 28800;
	p = gmtime(&tmt);

	pf = fopen(logpath, "a+");
	if(NULL != pf)
	{
		fprintf(pf, logformat, p->tm_year + 1900, p->tm_mon + 1, p->tm_mday, 32, wday[p->tm_wday], 32, p->tm_hour, p->tm_min, p->tm_sec, log_str);
		fclose(pf);
	}
}